import 'package:flutter/material.dart';

class MissingKeyProblemDemo extends StatefulWidget {
  @override
  _MissingKeyProblemDemoState createState() => _MissingKeyProblemDemoState();
}

class _MissingKeyProblemDemoState extends State<MissingKeyProblemDemo> {
  List<Map<String, dynamic>> items = [
    {'id': 1, 'name': '苹果', 'count': 0},
    {'id': 2, 'name': '香蕉', 'count': 0},
    {'id': 3, 'name': '橙子', 'count': 0},
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('缺少 Key 问题示例')),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                // 重新排序列表
                items.sort((a, b) => b['count'].compareTo(a['count']));
              });
            },
            child: Text('按计数排序'),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (context, index) {
                // 问题：没有使用 Key，可能导致状态混乱
                return Card(
                  // 缺少 key 属性
                  child: ListTile(
                    title: Text(items[index]['name']),
                    subtitle: Text('计数: ${items[index]['count']}'),
                    trailing: IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        setState(() {
                          items[index]['count']++;
                        });
                      },
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

// 修复版本
class FixedMissingKeyDemo extends StatefulWidget {
  @override
  _FixedMissingKeyDemoState createState() => _FixedMissingKeyDemoState();
}

class _FixedMissingKeyDemoState extends State<FixedMissingKeyDemo> {
  List<Map<String, dynamic>> items = [
    {'id': 1, 'name': '苹果', 'count': 0},
    {'id': 2, 'name': '香蕉', 'count': 0},
    {'id': 3, 'name': '橙子', 'count': 0},
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('修复 Key 问题示例')),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                items.sort((a, b) => b['count'].compareTo(a['count']));
              });
            },
            child: Text('按计数排序'),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (context, index) {
                return Card(
                  key: ValueKey(items[index]['id']), // 使用唯一 ID 作为 Key
                  child: ListTile(
                    title: Text(items[index]['name']),
                    subtitle: Text('计数: ${items[index]['count']}'),
                    trailing: IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        setState(() {
                          items[index]['count']++;
                        });
                      },
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    title: 'PageView Demo',
    debugShowCheckedModeBanner: false,
    home: FixedMissingKeyDemo(),
  ));
}
